import React, { Component } from 'react';
import { Table, Input, Button, Popconfirm, Form,Select, Modal,  Divider,Row,Col,DatePicker} from 'antd';
import Content from "../../components/Content/Content";
import moment from "moment";

const EditableContext = React.createContext();
const { Option } = Select;
const InputGroup = Input.Group;
const { TextArea } = Input;
const { Item } = Form;
const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);
const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} is required.`,
            },
          ],
          initialValue: record[dataIndex],
        })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingRight: 24 }}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: "序号",
        key: "id",
        dataIndex: "id",
        fixed: "left",
        width: 120,
      
      },
      {
        title: "化合物编号",
        key: "hhw_id",
        dataIndex: "hhw_id",
      },
      {
        title: "出库批次",
        key: "compound_ckpc",
        dataIndex: "compound_ckpc",
      },
      {
        title: "化合物数量",
        key: "compound_hhwsl",
        dataIndex: "compound_hhwsl"
      },
      {
        title: "筛选模型",
        key: "m_id",
        dataIndex: "m_id"
      },
      {
        title: "取样重量",
        key: "compound_weight",
        dataIndex: "compound_weight"
      },
      {
        title: "取样体积",
        key: "compound_purity",
        dataIndex: "compound_purity"
      },
      {
        title: "取样人",
        key: "user_person",
        dataIndex: "user_person"
      },
      {
        title: "所属单位",
        key: "compound_ssdw",
        dataIndex: "compound_ssdw"
      },
      {
        title: "所属科室",
        key: "compund_ssks",
        dataIndex: "compund_ssks"
      },
      {
        title: "化合物用途",
        key: "compound_hhwyt",
        dataIndex: "compound_hhwyt"
      },
      {
        title: "备注",
        key: "compound_remark",
        dataIndex: "compound_remark"
      },
      {
        title: "操作",
        dataIndex: "caozuo",
        fixed: "right",
        width: 360,
        render: (text, record) => (
          <span>
            <Button  type="dashed" onClick={() => this.showModal_view(record)}>
              查看
            </Button>
            <Divider type="vertical" />
            <Button type="dashed" onClick={() => this.showModal_edit(record)}>
              修改
            </Button>
            <Divider type="vertical" />
            <Button type="dashed" onClick={() => this.showModal_liufen(record.hhw_id)}>
              化合物编号
            </Button>
          </span>
        )
      }
    ];
    this.columns1 = [ ];
    this.columns2 = [ ];

    this.state = {
      dataSource: [
        {
          key: '0',
          name: ' 0',
          age: '32',
          address: ' no. 0',
        },
      ],
      count: 0,

      selectedRowKeys: [], // Check here to configure the default column

      loading: false,
      loading_out: false,
  
      searchParams: {},

      newData: {},

      visible_add: false,
      visible_batch: false,

      visible_edit: false,
      editData: {},

      visible_liufen: false,

      visible_view:false,
      viewData: {},
    };
  }

  showModal_add = () => {
    this.setState({
      visible_add: true,
      newData: {}
    });
  };
  handleOk_add = e => {
    this.setState({
      visible_add: false,
    });
  };
  handleCancel_add = e => {
    this.setState({
      visible_add: false,
    });
  };

  // 查看
  showModal_view = ( record ) => {
    this.setState({
      visible_view: true,
      viewData: record
    });
  };
  handleOk_view = e => {
    this.setState({
      visible_view: false,
    });
  };
  handleCancel_view = e => {
    this.setState({
      visible_view: false,
    });
  };

  // 留份
  showModal_liufen = ( id ) => {

    const url = global.api.compoundInfo ;
    return global.getdata.get(url, {hhw_id: id})
    .then(res => {
      this.setState({newData: {}, visible_liufen: true,})
    })
    .catch(err => {
      Modal.error({
        content: '网络异常!',
      });
    }) 

  };
  handleOk_liufen = e => {
    this.setState({
      visible_liufen: false,
    });
  };
  handleCancel_liufen = e => {
    this.setState({
      visible_liufen: false,
    });
  };


  showModal_batch = () => {
    this.setState({
      visible_batch: true,
    });
  };
  handleOk_batch = e => {
    this.setState({
      visible_batch: false,
    });
  };
  handleCancel_batch = e => {
    this.setState({
      visible_batch: false,
    });
  };

  showModal_edit = ( record ) => {
    this.setState({
      visible_edit: true,
      editData: record
    });
  };
  handleOk_edit = e => {
    this.setState({
      visible_edit: false,
    });
  };
  handleCancel_edit = e => {
    this.setState({
      visible_edit: false,
    });
  };

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };
  
  // 更新
  handleUpdate = () => {
    const url = global.api.compoundOut + this.state.editData.id + '/';
    return global.updatedata.put(url, this.state.editData)
    .then(res => {  
      Modal.success({
        content: '更新成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '更新出错!',
      });
    })    
  }

  // 保存
  handleSave = row => {
    const url = global.api.compoundOut;
    return global.network.post(url, this.state.newData)
    .then(res => {

      this.loadData(1)

      Modal.success({
        content: '保存成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '保存出错!',
      });
    })
  };

  // 导出到本地
  outToLocal = () => {
    this.setState({ loading_out: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading_out: false
      });
    }, 1000);

    let selectedRowKeys = this.state.selectedRowKeys;
    if(selectedRowKeys) {
      for( let x of selectedRowKeys ) {
        let record = this.state.dataSource[x];
        let id = record.id;
        // TODO 跳转到导出URL
      }
    }   

  };

  loadData = (current = 1) => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);

    const url = global.api.compoundOut
    + '?compound_ckpc=' + (this.state.searchParams.compound_ckpc || "")
    + '&compound_hhwsl=' + (this.state.searchParams.compound_hhwsl || "")
    + '&m_id=' + (this.state.searchParams.m_id || "")
    + '&compound_weight=' + (this.state.searchParams.compound_weight || "")
    + '&compound_purity=' + (this.state.searchParams.compound_purity || "")
    + '&user_person=' + (this.state.searchParams.user_person || "")
    + '&compound_ssdw=' + (this.state.searchParams.compound_ssdw || "");
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize, search: {}})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count})
    })
    .catch(err => {
      Modal.error({
        content: '网络异常!',
      });
    }) 
  }
  componentDidMount() {
    this.loadData(1);
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      }
    };
    
    const { dataSource,loading, selectedRowKeys } = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    const hasSelected = selectedRowKeys.length > 0;

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    const columns1= this.columns1.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    const columns2= this.columns2.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Content>
         <Form
          {...formItemLayout}
          onSubmit={this.onSubmit}
          colon={false}
          style={{ borderBottom: "20px solid #f0f2f5" }}
        >
          <Item label="出库批次">
            <Input onChange={e => this.state.searchParams.compound_ckpc = e.target.value} />
          </Item>
          <Item label="化合物数量">
            <Input onChange={e => this.state.searchParams.compound_hhwsl = e.target.value} />
          </Item>
          <Item label="筛选模型">
            <Input onChange={e => this.state.searchParams.m_id = e.target.value} />
          </Item>
          <Item label="取样重量">
            <Input onChange={e => this.state.searchParams.compound_weight = e.target.value} />
          </Item>
          <Item label="取样体积">
            <Input onChange={e => this.state.searchParams.compound_purity = e.target.value} />
          </Item>
          <Item label="取样人">
            <Input onChange={e => this.state.searchParams.user_person = e.target.value} />
          </Item>
          <Item label="所属单位">
            <Input onChange={e => this.state.searchParams.compound_ssdw = e.target.value} />
          </Item>
          <Item wrapperCol={{ span: 10, offset: 5 }}>
            <Row guuter={16}>
              <Col span={5}>
              <Button type="primary" onClick={()=>this.loadData(1)} loading={this.state.loading}>
                  精确查询
                </Button>
              </Col>
              <Col span={5}>
              </Col>
              <Col span={5}>
              </Col>
              <Col span={5}>
                
              </Col>
            </Row>
          </Item>
        </Form>

        <div style={{marginLeft: 16}}>
        <Button  disabled={!hasSelected} loading={this.state.loading_out} onClick={this.outToLocal} type="primary" >
          导出
        </Button>
        <Button  type="primary" onClick={this.showModal_add} style={{marginLeft: 16, marginTop: 16}}>
          化合物出库
        </Button>
        <Button  type="primary" onClick={this.showModal_batch} style={{marginLeft: 16, display: 'none'}}>
          批量出库
        </Button>
         </div>
         <Modal
          title="流份出库"
          visible={this.state.visible_add}
          onOk={this.handleOk_add}
          onCancel={this.handleCancel_add}
        >
         <Form
          {...formItemLayout}
          onSubmit={this.onSubmit}
          colon={false}

        >
           <div style={{ display: "flex" }}>
                <span style={{ flex: 1 }}>
                  <Item label="编号">
                    <Input onChange={e => this.state.newData.id = e.target.value} />
                  </Item>
                  <Item label="化合物编号">
                    <Input onChange={e => this.state.newData.hhw_id = e.target.value} />
                  </Item>
                  <Item label="出库批次">
                    <Input onChange={e => this.state.newData.compound_ckpc = e.target.value} />
                  </Item>
                  <Item label="化合物数量">
                    <Input onChange={e => this.state.newData.compound_hhwsl = e.target.value} />
                  </Item>
                  <Item label="取样重量">
                    <Input onChange={e => this.state.newData.compound_weight  = e.target.value} />
                  </Item>
                  <Item label="取样体积">
                    <Input onChange={e => this.state.newData.compound_purity  = e.target.value} />
                  </Item>
                  <Item label="取样时间">
                   <DatePicker format={'YYYY-MM-DD HH:mm:ss'} onChange={(date, dateStr) => this.state.newData.compound_time = dateStr} style={{ width: "100%" }} />{" "}
                  </Item>
                  <Item label="所属单位">
                    <Input onChange={e => this.state.newData.user_person = e.target.value} />
                  </Item>
                  <Item label="所属科室">
                    <Input onChange={e => this.state.newData.compund_ssks = e.target.value} />
                  </Item>
                  <Item label="化合物用途">
                    <Input onChange={e => this.state.newData.compound_hhwyt = e.target.value} />
                  </Item>
                  <Item label="备注">
                    <Input onChange={e => this.state.newData.compound_remark = e.target.value} />
                  </Item>

                  <Item label="&nbsp;">
                    <Button type="primary" loading={this.state.loading} onClick={this.handleSave}> 保存 </Button>          
                  </Item>                    
                    
                </span>
              </div>
            </Form>
        </Modal>
        <Modal
          title="批量出库"
          visible={this.state.visible_batch}
          onOk={this.handleOk_batch}
          onCancel={this.handleCancel_batch}
        >
        <Button  type="primary" style={{marginTop: '50px',marginLeft: 16}}>
        保存
        </Button>
        <Table
          rowSelection={rowSelection}
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns1}
          scroll={{ x: 2900}}
        />
        </Modal>
        <Modal
          title="查看"
          visible={this.state.visible_view}
          onOk={this.handleOk_view}
          onCancel={this.handleCancel_view}
        >
        <Form
          {...formItemLayout}
          onSubmit={this.onSubmit}
          colon={false}
        >
           <div style={{ display: "flex" }}>
                <span style={{ flex: 1 }}>
                <Item label="编号">
                    <Input readOnly defaultValue={this.state.viewData.id} />
                  </Item>
                  <Item label="化合物编号">
                    <Input readOnly defaultValue={this.state.viewData.hhw_id} />
                  </Item>
                  <Item label="出库批次">
                    <Input readOnly defaultValue={this.state.viewData.compound_ckpc} />
                  </Item>
                  <Item label="化合物数量">
                    <Input readOnly defaultValue={this.state.viewData.compound_hhwsl} />
                  </Item>
                  <Item label="取样重量">
                    <Input readOnly defaultValue={this.state.viewData.compound_weight } />
                  </Item>
                  <Item label="取样体积">
                    <Input readOnly defaultValue={this.state.viewData.compound_purity } />
                  </Item>
                  <Item label="取样时间">
                   <DatePicker defaultValue={moment(this.state.viewData.compound_time)} style={{ width: "100%" }} />{" "}
                  </Item>
                  <Item label="所属单位">
                    <Input readOnly defaultValue={this.state.viewData.user_person} />
                  </Item>
                  <Item label="所属科室">
                    <Input readOnly defaultValue={this.state.viewData.compund_ssks} />
                  </Item>
                  <Item label="化合物用途">
                    <Input readOnly defaultValue={this.state.viewData.compound_hhwyt} />
                  </Item>
                  <Item label="备注">
                    <Input readOnly defaultValue={this.state.viewData.compound_remark} />
                  </Item>

                </span>
              </div>
            </Form>
        </Modal>
        <Modal
          title="修改"
          visible={this.state.visible_edit}
          onOk={this.handleOk_edit}
          onCancel={this.handleCancel_edit}
        >
           <Form
          {...formItemLayout}
          onSubmit={this.onSubmit}
          colon={false}
        >
             
             <div style={{ display: "flex" }}>
                <span style={{ flex: 1 }}>
                <Item label="编号">
                    <Input readOnly defaultValue={this.state.editData.id} />
                  </Item>
                  <Item label="化合物编号">
                    <Input defaultValue={this.state.editData.hhw_id} onChange={e => this.state.editData.hhw_id = e.target.value} />
                  </Item>
                  <Item label="出库批次">
                    <Input defaultValue={this.state.editData.compound_ckpc} onChange={e => this.state.editData.compound_ckpc = e.target.value} />
                  </Item>
                  <Item label="化合物数量">
                    <Input defaultValue={this.state.editData.compound_hhwsl} onChange={e => this.state.editData.compound_hhwsl = e.target.value} />
                  </Item>
                  <Item label="取样重量">
                    <Input defaultValue={this.state.editData.compound_weight } onChange={e => this.state.editData.compound_weight = e.target.value} />
                  </Item>
                  <Item label="取样体积">
                    <Input defaultValue={this.state.editData.compound_purity } onChange={e => this.state.editData.compound_purity = e.target.value} />
                  </Item>
                  <Item label="取样时间">
                   <DatePicker defaultValue={moment(this.state.editData.compound_time)} style={{ width: "100%" }} onChange={(date, dateStr) => this.state.editData.compound_time = dateStr} />{" "}
                  </Item>
                  <Item label="所属单位">
                    <Input defaultValue={this.state.editData.user_person} onChange={e => this.state.editData.user_person = e.target.value} />
                  </Item>
                  <Item label="所属科室">
                    <Input defaultValue={this.state.editData.compund_ssks} onChange={e => this.state.editData.compund_ssks = e.target.value} />
                  </Item>
                  <Item label="化合物用途">
                    <Input defaultValue={this.state.editData.compound_hhwyt} onChange={e => this.state.editData.compound_hhwyt = e.target.value} />
                  </Item>
                  <Item label="备注">
                    <Input defaultValue={this.state.editData.compound_remark} onChange={e => this.state.editData.compound_remark = e.target.value} />
                  </Item>

                  <Item label="&nbsp;">
                    <Button type="primary" loading={this.state.loading} onClick={this.handleUpdate}> 保存 </Button>          
                  </Item>      

                </span>
              </div>
            </Form>
        </Modal>
        <Modal
          title="化合物编号"
          visible={this.state.visible4}
          onOk={this.handleOk4}
          onCancel={this.handleCancel4}
        >
           <Button  type="primary" style={{marginTop: 12,marginLeft: 16}}>
          导出
        </Button>
         <Table
          rowSelection={rowSelection}
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns2}
          scroll={{ x: 4000, y: 300 }}
        />
        </Modal>
        <Table
          rowSelection={rowSelection}
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
          scroll={{x:2000}}
        />
      </Content>
    );
  }
}

const ScreeningSaveInfo = Form.create()(EditableTable);
export default ScreeningSaveInfo;